import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
@Component({
	selector: 'sa-firmware-operation',
	templateUrl: './firmware-operation.component.html',
})
export class FirmwareOperationComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	selectedCompanyName: string = ''; //公司名称
	selectedCompanyId: string = '';//公司ID
	useTypeL1: string = '';//useTypeL1  select值
	useTypeL2: string = '';//useTypeL2  select值
	hwVersion: string = ''
	sensorNum: string = ''
	hwVersionList: any = [] //硬件版本数据
	sensorNumList: any = [] //通道数数据
	btnData: any[] = [];
	binDeleteBatch: boolean = false;
	carTypeList = carTypeListObj.carTypeList
	carUseList = carTypeListObj.carUseList
	carDeatailUseList = carTypeListObj.carDeatailUseList
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	// 获取省份列表
	getObtainHwVersionAndSensorNum() {
		this.jsonApiService.http_get('bininfoForOM/obtainHwVersionAndSensorNum.html').subscribe(data => {
		  if (data.success) {
			this.hwVersionList = data.data.hwVersions
			this.sensorNumList = data.data.sensorNums
		  }
		})
	  }
	ngOnInit() {
		this.initBtn();
		this.load();

		this.initAllBinName()
		this.getObtainHwVersionAndSensorNum() // 获取硬件版本和通道数列表数据
	}
	//刷新
	refresh() {
		this.load();
	}
	initBtn() {
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_bin:bininfo')));
		if (!this.btnData) { return };
		for (let item of this.btnData) {
			if (item.sourceKey === "bin:deleteBatch" && item.parentId) {
				this.binDeleteBatch = true;
			}
		}
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		let tableSearch = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				companyName: this.selectedCompanyName,
				companyId: this.selectedCompanyId,
				hwVersion: this.hwVersion,
				sensorNum: this.sensorNum,
				useTypeL2: $('#TcarTypeSelect2').val(),
				useTypeL1: $('#TcarTypeSelect2').val().slice(0, 2)
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(tableSearch);
		this.jsonApiService.http("bininfoForOM/list.html", reqdata).subscribe(data => {
			for (let item of data.exhibitDatas) {
				item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
				item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	getUseTypeNameL1(key) {
		if (key) {
			return this.carUseList[key];
		} else {
			return '';
		}
	}
	getUseTypeNameL2(key) {
		if (key) {
			return this.carDeatailUseList[key];
		} else {
			return '';
		}
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//新建调度任务
	new_scheduling() {
		this.router.navigate(['/system-config/firmware-operation/firmware-page'], { queryParams: { type: 'new' } });
	}
	//删除
	del_bin(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'ids=' + row.id;
			this.jsonApiService.http("bininfo/deleteBatch.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}
	/**
	 * 系数设置模块==================================================================================
	 */
	coefficientList: any = [];// 系数List
	coefParam: any = {
		id: '',
		coefSetStatus: '0', // 系数类型,默认系数高亮
	}
	// 系数设置
	coefConfig(row, modal) {
		this.jsonApiService.http_obj("bininfoForOM/getBinInfoById.html", { id: row.id }).subscribe(data => {
			if (data.success) {
				this.coefParam.coefSetStatus = data.data.coefSetStatus + '';
				this.initCoefficientList(data.data.coef);
				modal.show();
			}
		})
		this.coefParam.id = row.id;
	}
	// 系数类型选择
	coefConfigTypeChange(val) {
		this.coefParam.coefSetStatus = val;
	}
	// 初始化固定系数List
	initCoefficientList(data) {
		this.coefficientList = [];
		if (data && data.length > 0) {
			for (let i = 0; i < data.length; i++) {
				let obj = {
					coef: data[i],
					index: (i + 1),
				}
				this.coefficientList.push(obj);
			}
		} else {
			for (let i = 0; i < 16; i++) {
				let obj = {
					coef: '',
					index: (i + 1),
				}
				this.coefficientList.push(obj);
			}
		}
	}
	// 系数设置取消
	closeCoefConfig(modal) {
		modal.hide();
	}
	// 系数设置提交
	submitCoefConfig(modal) {
		if (this.coefParam.coefSetStatus == '1') {
			for (let item of this.coefficientList) {
				let keys = 'channel' + item.index;
				this.coefParam[keys] = item.coef;
			}
		}
		this.jsonApiService.confirm_message("确定要进行系数设置?").then(() => {
			this.jsonApiService.http_obj("bininfoForOM/updateCoefSetStatus.html", this.coefParam).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					modal.hide();
				}
			})
		})
	}
	/**
	 * 升级设置模块==================================================================================
	 */
	updateParam: any = {
		id: '',
		upgradeSetStatus: '0',// 默认: 系数设置不成功-允许升级固件
	}
	// 固件升级
	updateConfig(row, modal) {
		this.updateParam.id = row.id;
		this.jsonApiService.http_obj("bininfoForOM/getBinInfoById.html", { id: row.id }).subscribe(data => {
			if (data.success) {
				this.updateParam.upgradeSetStatus = data.data.upgradeSetStatus + '';
				modal.show();
			}
		})
	}
	// 升级类型设置
	updateConfigTypeChange(val) {
		this.updateParam.upgradeSetStatus = val;
	}
	// 取消升级设置
	closeUpdateConfig(modal) {
		modal.hide();
	}
	// 提交升级设置
	submitUpdateConfig(modal) {
		this.jsonApiService.confirm_message("确定要进行升级设置?").then(() => {
			this.jsonApiService.http_obj("bininfoForOM/updateUpgradeSetStatus.html", this.updateParam).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					modal.hide();
				}
			})
		})
	}

	//删除列
	deleteConfig(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("bininfoForOM/delBinInfoForOM.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				this.load();
			})
		})
	}


	// 替换固件
	binFrom = {
		binIdBefore: '',
		binIdAfter: ''
	}

	binBeforeList = [] // 固件替换当前的版本 list
	binAfterList = [] // 替换后的版本 list

	replaceBinNum = 0 // 替换条数

	isResetSelected: boolean = false  // 是否勾选
	resetSelectClick() {
		this.isResetSelected = !this.isResetSelected
	}
	initBinForm() {
		const that = this
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				$('#binBeforeSelect2').select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					templateResult: (state) => that.formatState(state, that),
					data: that.binBeforeList,//为Select添加数据
				}).on('select2:select', function (e) {
					that.isResetSelected = false
					const data = e.params ? e.params.data : {}
					that.binFrom.binIdBefore = data.id
					if (that.binFrom.binIdBefore) that.getReplaceNum()
				})

				$('#binIdAfterSelect2').select2({
					language: "zh-CN",
					placeholder: "请选择",
					allowClear: true,
					templateResult: (state) => that.formatState(state, that),
					data: that.binAfterList
				}).on('select2:select', function (e) {
					that.isResetSelected = false
					const data = e.params ? e.params.data : {}
					that.binFrom.binIdAfter = data.id
				})
			})
		})


	}
	formatState(state, that) {
		const { hwVersion, useTypeL2 } = state
		const type = that.getUseTypeNameL2(useTypeL2)
		let result = state.text
		if (type) result += `【${type}】`
		if (hwVersion) result += `【V${hwVersion}】`
		return result
	}


	getReplaceNum() {
		this.jsonApiService.http('bininfoForOM/getReplaceNums.html', 'binIdBefore=' + this.binFrom.binIdBefore).subscribe(data => {
			if (data.success)
				this.replaceBinNum = data.data
		})
	}
	// 清空选中
	delBin(id) {
		// 清空输入框值，需要手动触发 change
		$('#' + id).val('');
		$('#' + id).trigger('change');
		// 手动触发 select2:select，清空回调中的处理
		$('#' + id).trigger({
			type: 'select2:select',
			params: {
				data: {
					id: '',
					text: '',
				}
			}
		});
	}

	firmReplace(modal) {

		this.delBin("binBeforeSelect2")
		this.delBin("binIdAfterSelect2")
		this.isResetSelected = false
		this.replaceBinNum = 0
		modal.show();
	}

	// 获取所有 bin list
	initAllBinName() {
		const that = this
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http('bininfo/bininfoListByBinName.html', null).subscribe(data => {
				if (data.success) {
					const binList = data.data
					const selections = []
					for (var i = 0; i < binList.length; i++) {
						const obj = {
							id: binList[i].id,
							text: binList[i].binName,
							useTypeL2: binList[i].useTypeL2,
							hwVersion: binList[i].hwVersion
						}
						selections.push(obj)
					}
					that.binBeforeList = selections

					that.binAfterList = selections.map(el => ({ ...el }))
					that.initBinForm()
				}
				resolve(null)
			})
		})
	}


	submitReplaceCommit(modal) {
		if (!this.binFrom.binIdBefore) {
			this.jsonApiService.message('请选择替换的固件版本');
			return
		}
		if (!this.binFrom.binIdAfter) {
			this.jsonApiService.message('请选择用于替换的固件版本');
			return
		}

		if (!this.isResetSelected) {
			this.jsonApiService.message('高危操作，请确认替换记录数量');
			return
		}

		this.jsonApiService.http('bininfoForOM/replaceBinInfo.html', 'binIdBefore=' + this.binFrom.binIdBefore + '&binIdAfter=' + this.binFrom.binIdAfter).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.load();
				modal.hide();
			}
		})
	}
}